<script setup lang="ts">
import {onBeforeUnmount, computed, PropType, unref, nextTick, ref, watch, shallowRef} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {IDomEditor, IEditorConfig, i18nChangeLanguage} from '@wangeditor/editor'
import {propTypes} from '@/utils/propTypes'
import {isNumber} from '@/utils/is'
import {ElMessage} from 'element-plus'
import {useLocaleStore} from '@/store/modules/locale'
import {useStorage} from "@/hooks/web/useStorage";
import {fileUpload} from "@/api/content";
import axios from "axios";

const {getStorage} = useStorage()
const localeStore = useLocaleStore()

const currentLocale = computed(() => localeStore.getCurrentLocale)

i18nChangeLanguage(unref(currentLocale).lang)

const props = defineProps({
  editorId: propTypes.string.def('wangeEditor-1'),
  height: propTypes.oneOfType([Number, String]).def('500px'),
  editorConfig: {
    type: Object as PropType<IEditorConfig>,
    default: () => undefined
  },
  modelValue: propTypes.string.def('')
})

const emit = defineEmits(['change', 'update:modelValue'])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<IDomEditor>()

const valueHtml = ref('')

watch(
    () => props.modelValue,
    (val: string) => {
      if (val === unref(valueHtml)) return
      valueHtml.value = val
    },
    {
      immediate: true
    }
)

// 监听
watch(
    () => valueHtml.value,
    (val: string) => {
      emit('update:modelValue', val)
    }
)

const handleCreated = (editor: IDomEditor) => {
  console.log('handleCreated')
  nextTick(() => {
    editorRef.value = editor
  })
}

// 编辑器配置
const editorConfig = computed((): IEditorConfig => {
  return Object.assign(
      {
        readOnly: false,
        customAlert: (s: string, t: string) => {
          switch (t) {
            case 'success':
              ElMessage.success(s)
              break
            case 'info':
              ElMessage.info(s)
              break
            case 'warning':
              ElMessage.warning(s)
              break
            case 'error':
              ElMessage.error(s)
              break
            default:
              ElMessage.info(s)
              break
          }
        },
        autoFocus: false,
        scroll: true,
        uploadImgShowBase64: true,
        MENU_CONF: {
          uploadImage: {
            async customUpload(file, insertFn) {
              let fileSize = file.size
              let maxSize = 1 * 1024 * 1024
              if (fileSize > maxSize) {
                return ElMessage({type: 'error', message: '上传图片大小不能超过1MB'})
              }
              let formdata = new FormData()
              formdata.append('file', file)
              axios.post('http://12.test.edu365.cn/api/index/upload', formdata, {
                headers: {
                  Token: getStorage('userInfo').token
                },
              }).then(res => {
                if (res.data.code == 0) {
                  insertFn('http://12.test.edu365.cn' + res.data.data.url);
                }
              })
            },
            server: 'http://12.test.edu365.cn/api/article/upload',
            // form-data fieldName ，默认值 'wangeditor-uploaded-image'
            fieldName: 'file',

            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024, // 1M

            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,

            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],

            // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。

            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            headers: {
              Token: getStorage('userInfo').token
            },

            // 跨域是否传递 cookie ，默认为 false
            // withCredentials: true,

            // 超时时间，默认为 10 秒
            timeout: 5 * 1000, // 5 秒
          },

          uploadVideo: {
            server: 'http://12.test.edu365.cn/api/article/upload',
            // form-data fieldName ，默认值 'wangeditor-uploaded-image'
            fieldName: 'file',

            async customUpload(file, insertFn) {
              let fileSize = file.size
              let maxSize = 5 * 1024 * 1024
              if (fileSize > maxSize) {
                return ElMessage({type: 'error', message: '上传视频大小不能超过5MB'})
              }
              let formdata = new FormData()
              formdata.append('file', file)
              axios.post('http://12.test.edu365.cn/api/index/upload', formdata, {
                headers: {
                  Token: getStorage('userInfo').token
                },
              }).then(res => {
                if (res.data.code == 0) {
                  insertFn('http://12.test.edu365.cn' + res.data.data.url);
                }
                console.log('url', import.meta.env.VITE_FILE_BASE_PATH + res.data.data.url);
              })
            },

            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 10 * 1024 * 1024, // 10M

            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,

            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['video/*'],

            // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。

            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            headers: {
              Token: getStorage('userInfo').token
            },

            // 超时时间，默认为 30 秒
            timeout: 15 * 1000, // 15 秒
          }

        }
      },
      props.editorConfig || {}
  )
})


const editorStyle = computed(() => {
  return {
    height: isNumber(props.height) ? `${props.height}px` : props.height
  }
})

// 回调函数
const handleChange = (editor: IDomEditor) => {
  emit('change', editor)
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = unref(editorRef.value)

  // 销毁，并移除 editor
  editor?.destroy()
})

const getEditorRef = async (): Promise<IDomEditor> => {
  await nextTick()
  return unref(editorRef.value) as IDomEditor
}

defineExpose({
  getEditorRef
})
</script>

<template>
  <div class="border-1 border-solid border-[var(--el-border-color)] z-10">
    <!-- 工具栏 -->
    <Toolbar
        :editor="editorRef"
        :editorId="editorId"
        class="border-0 b-b-1 border-solid border-[var(--el-border-color)]"
    />
    <!-- 编辑器 -->
    <Editor
        v-model="valueHtml"
        :editorId="editorId"
        :defaultConfig="editorConfig"
        :style="editorStyle"
        @on-change="handleChange"
        @on-created="handleCreated"
    />
  </div>
</template>

<style src="@wangeditor/editor/dist/css/style.css"></style>
